<template>
  <div class="orders-page">
    <!-- 顶部统计卡片 -->
    <section class="hero">
      <div class="kpi">
        <div class="kpi-item">
          <div class="kpi-num">¥ {{ kpiAmount.toLocaleString() }}</div>
          <div class="kpi-label">本页订单总额</div>
        </div>
        <div class="kpi-item">
          <div class="kpi-num">{{ total }}</div>
          <div class="kpi-label">符合条件的订单数</div>
        </div>
        <div class="kpi-item">
          <div class="kpi-num">{{ selectedIds.length }}</div>
          <div class="kpi-label">已选中</div>
        </div>
      </div>

      <div class="hero-illustration">
        <div ref="chartRef" class="hero-chart"></div>
      </div>
    </section>

    <!-- 查询 -->
    <el-card class="search-card" shadow="hover">
      <el-form :inline="true" :model="query" class="search-form">
        <el-form-item label="订单号">
          <el-input v-model="query.order_no" placeholder="请输入订单号" clearable />
        </el-form-item>

        <el-form-item label="买家姓名">
          <el-input v-model="query.buyer_name" placeholder="请输入买家姓名" clearable />
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker
              v-model="queryRange.create"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始"
              end-placeholder="结束"
              value-format="YYYY-MM-DDTHH:mm:ss"
              style="width: 320px"
              clearable
          />
        </el-form-item>

        <el-form-item label="金额区间(¥)">
          <el-input-number v-model="query.amountMin" :min="0" :step="10" placeholder="最小" />
          <span class="tilde">~</span>
          <el-input-number v-model="query.amountMax" :min="0" :step="10" placeholder="最大" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
          <el-button @click="reset">重置</el-button>
          <el-button type="success" @click="openAdd">新增订单</el-button>
          <el-button type="danger" :disabled="!selectedIds.length" @click="batchDelete">批量删除</el-button>
          <el-button @click="exportCSV">导出CSV</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-card shadow="hover">
      <el-table
          ref="tableRef"
          v-loading="loading"
          :data="table"
          style="width: 100%"
          @selection-change="onSelectionChange"
          row-key="order_id"
          :header-cell-style="{ background: 'var(--el-fill-color-light)', fontWeight: 600 }"
      >
        <el-table-column type="selection" width="48" />
        <el-table-column type="expand" width="40">
          <template #default="{ row }">
            <div class="expand-box">
              <div><b>收货地址：</b>{{ row.delivery_addr || '—' }}</div>
              <div><b>创建时间：</b>{{ displayDateTime(row.create_time) || '—' }}</div>
              <div><b>订单号：</b>{{ row.order_no }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="order_no" label="订单号" min-width="160" />

        <el-table-column label="买家姓名" min-width="140" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.buyer_name || row.user_name || row.real_name || row.buyerName || '-' }}
          </template>
        </el-table-column>

        <el-table-column prop="total_amount" label="金额(¥)" width="120" sortable>
          <template #default="{ row }">¥ {{ toMoney(row.total_amount) }}</template>
        </el-table-column>

        <el-table-column prop="create_time" label="创建时间" min-width="180" sortable>
          <template #default="{ row }">
            {{ displayDateTime(row.create_time) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="openEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="remove(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          class="pagination"
          v-model:current-page="query.current"
          v-model:page-size="query.limit"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 50, 100]"
          @current-change="load"
          @size-change="onSizeChange"
      />
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.mode === 'add' ? '新增订单' : '编辑订单'" width="560px">
      <el-form :model="form" label-width="100px">
        <el-form-item label="订单号" required>
          <el-input v-model="form.order_no" placeholder="例如：ORD2025XXXX" />
        </el-form-item>
        <el-form-item label="买家ID" required>
          <el-input v-model="form.buyer_user_id" placeholder="买家 user_id" />
        </el-form-item>
        <el-form-item label="金额(¥)" required>
          <el-input-number v-model="form.total_amount" :min="0" :step="1" />
        </el-form-item>
        <el-form-item label="创建时间" required>
          <el-date-picker
              v-model="form.create_time"
              type="datetime"
              placeholder="选择时间"
              value-format="YYYY-MM-DDTHH:mm:ss"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="收货地址">
          <el-input v-model="form.delivery_addr" type="textarea" :rows="3" placeholder="详细地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import * as echarts from 'echarts';
import api from '@/api/orders_api.js';

/** 工具：把任意可能的时间字符串规范成 yyyy-MM-dd'T'HH:mm:ss */
const normalizeDateTime = (v) => {
  if (!v) return '';
  // Date 对象
  if (v instanceof Date && !isNaN(v)) {
    return v.toISOString().slice(0, 19); // 自带 T
  }
  // 字符串：先去掉毫秒和时区
  let s = String(v).trim();
  // 已经是 ISO 基本 OK（含 T）
  if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/.test(s)) return s;
  // 常见的 "yyyy-MM-dd HH:mm:ss" -> 替换空格为 T
  if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(s)) return s.replace(' ', 'T');
  // 只有日期 "yyyy-MM-dd" -> 补零时分秒
  if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return `${s}T00:00:00`;
  // 其他情况尝试 new Date 兜底
  const d = new Date(s);
  if (!isNaN(d)) return d.toISOString().slice(0, 19);
  return s; // 最后兜底，不改动（方便排查）
};

/** 仅用于显示：把 T 显示为空格 */
const displayDateTime = (v) => (v ? String(v).replace('T', ' ') : '');

const loading = ref(false);
const table = ref([]);
const total = ref(0);
const tableRef = ref();
const selectedIds = ref([]);

const toMoney = (v) => Number(v || 0).toFixed(2);

const kpiAmount = computed(
    () => (table.value || []).reduce((s, it) => s + Number(it.total_amount || 0), 0)
);

const query = ref({
  current: 1,
  limit: 10,
  order_no: '',
  buyer_name: '',
  amountMin: null,
  amountMax: null,
  createStart: '',
  createEnd: ''
});
const queryRange = ref({ create: [] });

/* 图表联动（按天汇总） */
const chartRef = ref(null);
let chartInstance = null;

const getDailySeries = () => {
  const grouped = {};
  (table.value || []).forEach(it => {
    const day = String(it.create_time || '').slice(0, 10); // yyyy-MM-dd
    if (!day) return;
    grouped[day] = (grouped[day] || 0) + Number(it.total_amount || 0);
  });
  const days = Object.keys(grouped).sort();
  return { x: days, y: days.map(d => Number(grouped[d].toFixed(2))) };
};

const renderChart = () => {
  if (!chartRef.value) return;
  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value);
    window.addEventListener('resize', resizeChart);
  }
  const { x, y } = getDailySeries();
  chartInstance.setOption({
    grid: { left: 24, right: 18, top: 24, bottom: 22 },
    tooltip: { trigger: 'axis', valueFormatter: (v) => `¥ ${Number(v || 0).toLocaleString()}` },
    xAxis: {
      type: 'category',
      data: x,
      boundaryGap: false,
      axisTick: { show: false },
      axisLine: { lineStyle: { color: '#A5D6A7' } }
    },
    yAxis: {
      type: 'value',
      axisLine: { show: false },
      splitLine: { lineStyle: { color: '#E0F2F1' } },
      axisLabel: { formatter: (v) => (v >= 1000 ? `${v/1000}k` : v) }
    },
    series: [{
      name: '订单总额',
      type: 'line',
      smooth: true,
      symbol: 'circle',
      showSymbol: y.length <= 20,
      lineStyle: { width: 3 },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(102,187,106,0.35)' },
          { offset: 1, color: 'rgba(102,187,106,0.00)' }
        ])
      },
      data: y
    }],
    animationDuration: 600
  });
};

const resizeChart = () => { if (chartInstance) chartInstance.resize(); };
watch(table, renderChart, { deep: true });
onMounted(() => { load().then(renderChart); });
onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart);
  if (chartInstance) { chartInstance.dispose(); chartInstance = null; }
});

/* 数据加载 */
const cleanEmpty = (obj) => {
  const r = {};
  Object.entries(obj).forEach(([k, v]) => {
    if (v !== '' && v !== null && v !== undefined) r[k] = v;
  });
  return r;
};

const load = async () => {
  loading.value = true;
  try {
    // 从时间范围选择器同步到 query，并做一次规范
    query.value.createStart = normalizeDateTime(queryRange.value.create?.[0] || '');
    query.value.createEnd   = normalizeDateTime(queryRange.value.create?.[1] || '');

    const res = await api.page(cleanEmpty(query.value));

    const root = res?.data ?? res ?? {};
    const box  = root.data ?? root;

    let list =
        (Array.isArray(box) ? box : null) ||
        box.data || box.list || box.records || box.rows || [];

    if (!Array.isArray(list) && Array.isArray(box?.data?.data)) {
      list = box.data.data;
    }

    let totalCnt =
        root.total ?? root.count ??
        box.total ?? box.count ??
        box?.data?.total ?? box?.data?.count ??
        (Array.isArray(list) ? list.length : 0);

    // 统一把 create_time 规范为带 T 的字符串
    table.value = (list || []).map(it => {
      const create = it.create_time ?? it.createTime ?? '';
      return {
        order_id      : it.order_id ?? it.id,
        order_no      : it.order_no ?? it.orderNo,
        buyer_user_id : it.buyer_user_id ?? it.buyerUserId ?? it.buyer_id ?? it.buyerId ?? it.buyer_name,
        buyer_name    : it.buyer_name ?? it.user_name ?? it.real_name ?? it.buyerName ?? it.userName,
        total_amount  : it.total_amount ?? it.totalAmount,
        create_time   : normalizeDateTime(create),
        delivery_addr : it.delivery_addr ?? it.deliveryAddr,
        ...it
      };
    });

    total.value = Number(totalCnt) || 0;
  } catch (e) {
    console.error(e);
    ElMessage.error('加载失败');
    table.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

/* 交互 */
const search = () => { query.value.current = 1; load(); };

const reset = () => {
  query.value = {
    current: 1, limit: 10,
    order_no: '', buyer_name: '',
    amountMin: null, amountMax: null,
    createStart: '', createEnd: ''
  };
  queryRange.value.create = [];
  load();
};

const onSizeChange = (size) => { query.value.limit = size; query.value.current = 1; load(); };
const onSelectionChange = (rows) => { selectedIds.value = (rows || []).map(r => r.order_id); };

const dialog = ref({ visible: false, mode: 'add' });
const form = ref({
  order_id: null,
  order_no: '',
  buyer_user_id: '',   // 表单内一致用 buyer_user_id
  total_amount: 0,
  create_time: '',
  delivery_addr: '',
});

const openAdd = () => {
  dialog.value = { visible: true, mode: 'add' };
  form.value = {
    order_id: null,
    order_no: '',
    buyer_user_id: '',
    total_amount: 0,
    create_time: normalizeDateTime(new Date()), // 带 T
    delivery_addr: ''
  };
};

const openEdit = (row) => {
  dialog.value = { visible: true, mode: 'edit' };
  form.value = {
    order_id: row.order_id,
    order_no: row.order_no,
    buyer_user_id: row.buyer_user_id,                 // 同一字段
    total_amount: Number(row.total_amount || 0),
    create_time: normalizeDateTime(row.create_time),  // 统一规范
    delivery_addr: row.delivery_addr
  };
};

const submit = async () => {
  if (!form.value.order_no) return ElMessage.warning('请输入订单号');
  if (!form.value.buyer_user_id) return ElMessage.warning('请输入买家ID');
  if (form.value.total_amount == null || Number(form.value.total_amount) < 0)
    return ElMessage.warning('请输入正确金额');
  if (!form.value.create_time) return ElMessage.warning('请选择创建时间');

  // 最终再规范一次，保证一定是 yyyy-MM-dd'T'HH:mm:ss
  const payload = {
    order_no: form.value.order_no,
    buyer_id: form.value.buyer_user_id, // 映射为后端字段
    total_amount: Number(form.value.total_amount || 0),
    create_time: normalizeDateTime(form.value.create_time),
    delivery_addr: form.value.delivery_addr || ''
  };

  try {
    if (dialog.value.mode === 'add') {
      await api.add(payload);
      ElMessage.success('新增成功');
    } else {
      await api.edit({ order_id: form.value.order_id, ...payload });
      ElMessage.success('修改成功');
    }
    dialog.value.visible = false;
    load();
  } catch (e) {
    console.error(e);
    ElMessage.error('保存失败');
  }
};

const remove = async (row) => {
  try {
    await ElMessageBox.confirm(`确定删除订单 #${row.order_no} 吗？`, '提示', { type: 'warning' });
    await api.del(row.order_id);
    ElMessage.success('删除成功');
    load();
  } catch (e) {
    if (e !== 'cancel') {
      console.error(e);
      ElMessage.error('删除失败');
    }
  }
};

const batchDelete = async () => {
  if (!selectedIds.value.length) return;
  try {
    await ElMessageBox.confirm(`确定删除已选中的 ${selectedIds.value.length} 条订单吗？`, '提示', { type: 'warning' });
    await Promise.all(selectedIds.value.map(id => api.del(id)));
    ElMessage.success('批量删除成功');
    selectedIds.value = [];
    load();
  } catch (e) {
    if (e !== 'cancel') {
      console.error(e);
      ElMessage.error('批量删除失败');
    }
  }
};

const exportCSV = () => {
  const rows = table.value || [];
  if (!rows.length) return ElMessage.warning('没有可导出的数据');

  const headers = ['order_id','order_no','buyer_user_id','buyer_name','total_amount','create_time','delivery_addr'];
  const lines = [
    headers.join(','),
    ...rows.map(r => [
      r.order_id,
      `"${(r.order_no || '').replace(/"/g,'""')}"`,
      r.buyer_user_id,
      `"${(r.buyer_name || r.user_name || r.real_name || '').replace(/"/g,'""')}"`,
      r.total_amount,
      `"${displayDateTime(r.create_time).replace(/"/g,'""')}"`, // 导出时显示空格更友好
      `"${(r.delivery_addr || '').replace(/"/g,'""')}"`,
    ].join(','))
  ];
  const blob = new Blob([lines.join('\n')], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `orders_${Date.now()}.csv`;
  a.click();
  URL.revokeObjectURL(url);
};
</script>

<style scoped>
.orders-page { padding: 16px; }

/* 顶部 KPI */
.hero {
  display: grid;
  grid-template-columns: 1.2fr 0.8fr;
  gap: 12px;
  margin-bottom: 14px;
}
.kpi {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
}
.kpi-item {
  border: 1px solid #e0f2f1;
  background: linear-gradient(180deg, #f5fff7, #ffffff);
  border-radius: 12px;
  padding: 14px;
  box-shadow: 0 6px 16px rgba(76,175,80,0.08);
}
.kpi-num { font-size: 20px; font-weight: 800; color: #2e7d32; }
.kpi-label { color: #607d8b; font-size: 12px; margin-top: 4px; }

/* 图表卡片 */
.hero-illustration {
  border: 1px solid #e0f2f1;
  border-radius: 12px;
  background: #f9fff9;
  padding: 8px;
  display: grid;
}
.hero-chart {
  width: 100%;
  height: 200px;
  border-radius: 10px;
}

/* 搜索卡片与表单 */
.search-card { margin-bottom: 12px; }
.search-form :deep(.el-input-number) { width: 140px; }
.tilde { margin: 0 6px; color: #90a4ae; }

/* 展开区 */
.expand-box {
  padding: 8px 12px;
  background: #f9fff9;
  border: 1px dashed #c8e6c9;
  border-radius: 8px;
  line-height: 1.8;
}

/* 分页 */
.pagination { margin-top: 12px; justify-content: center; }

@media (max-width: 1024px) {
  .hero { grid-template-columns: 1fr; }
  .kpi { grid-template-columns: 1fr 1fr 1fr; }
}
@media (max-width: 640px) {
  .kpi { grid-template-columns: 1fr; }
}
</style>
